package com.wsfPro.security.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {
  @Override
  public void decide(
      Authentication authentication, Object o, Collection<ConfigAttribute> collection)
      throws AccessDeniedException, AuthenticationException {
    Iterator<ConfigAttribute> iterator = collection.iterator();
    String param = null;
    while (iterator.hasNext()) {
      ConfigAttribute ca = iterator.next();
      // 当前请求需要的权限
      String needRole = ca.getAttribute();
      param = "ROLE_LOGIN";
      if (param.equals(needRole)) {
        //        AnonymousAuthenticationToken匿名认证
        if (authentication instanceof AnonymousAuthenticationToken) {
          //          未登陆不允许匿名访问
          param = "无权限或无法访问的资源";
          throw new BadCredentialsException(param);
        }
      }
      // 当前用户所具有的权限
      Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
      for (GrantedAuthority authority : authorities) {
        // 如果当前用户所拥有的角色权限匹配上该url菜单对应的其中一个角色的权限则有权访问该url接口则检验成功直接return
        if (authority.getAuthority().equals(needRole)) {
          return;
        }
      }
    }
    param = "权限不足!";
    throw new AccessDeniedException(param);
  }

  @Override
  public boolean supports(ConfigAttribute configAttribute) {
    return true;
  }

  @Override
  public boolean supports(Class<?> aClass) {
    return true;
  }
}
